<template>
    <div id="nav">
        <nav class="navbar navbar-expand-md navbar-light shadow-sm">
            <div style="margin-right: 25px;cursor: pointer">
                <img src="/static/img/favicon.svg" alt="logo">
            </div>
            <a class="navbar-brand welcome" href="#">{{/*info.username*/}}</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavbar">

                <!--左侧区域-->
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/user/userInfo">用户管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/student/info">学生管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/file/fileManage">文件管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/file/upload">上传文件</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/file/fileList">文件列表</a>
                    </li>
                    <!--下拉菜单-->
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
                            文件
                        </a>
                        <div class="dropdown-menu">
                            <!--下拉菜单-->
                        </div>
                    </li>
                </ul>

                <!--右侧区域-->
                <ul class="nav navbar-nav ml-auto">
                    <li class="nav-item avatar-li">
                        <!--头像-->
                        <div class="avatar-container">
                            <a data-toggle="modal" data-target="#avatar-modal" id="avatar">
                                <img src="info.avatar" class="img-fluid rounded-circle img-thumbnail" alt="头像">
                            </a>

                            <!--头像二级菜单-->
                            <div class="menu avatar-menu">
                                <div class="avatar-menu-img" data-toggle="modal" data-target="#avatar-modal">
                                    <img src="info.avatar" class="img-fluid rounded-circle img-thumbnail" alt="头像">
                                </div>
                                <div class="avatar-menu-content">
                                    <p>{{/*info.username*/}}</p>
                                    <span>年度会员</span>
                                    <div class="level">
                                        <span>等级5</span>
                                        <span style="color: grey;font-size: 10px;">9999/N</span>
                                    </div>
                                    <!--进度条-->
                                    <div class="level-bar">
                                        <div class="level-progress"></div>
                                    </div>
                                    <div class="links">
                                        <a target="_blank" class="link-item text-decoration-none text-muted" data-toggle="modal" data-target="#loginInfoModal">
                                            <div data-v-59fd5a91="" class="link-title">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-key" viewBox="0 0 16 16">
                                                    <path d="M0 8a4 4 0 0 1 7.465-2H14a.5.5 0 0 1 .354.146l1.5 1.5a.5.5 0 0 1 0 .708l-1.5 1.5a.5.5 0 0 1-.708 0L13 9.207l-.646.647a.5.5 0 0 1-.708 0L11 9.207l-.646.647a.5.5 0 0 1-.708 0L9 9.207l-.646.647A.5.5 0 0 1 8 10h-.535A4 4 0 0 1 0 8zm4-3a3 3 0 1 0 2.712 4.285A.5.5 0 0 1 7.163 9h.63l.853-.854a.5.5 0 0 1 .708 0l.646.647.646-.647a.5.5 0 0 1 .708 0l.646.647.646-.647a.5.5 0 0 1 .708 0l.646.647.793-.793-1-1h-6.63a.5.5 0 0 1-.451-.285A3 3 0 0 0 4 5z"/>
                                                    <path d="M4 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
                                                </svg>
                                                修改密码
                                            </div>
                                        </a>
                                        <a href="#" target="_blank" class="link-item text-decoration-none text-muted">
                                            <div data-v-59fd5a91="" class="link-title">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-journal-bookmark" viewBox="0 0 16 16">
                                                    <path fill-rule="evenodd" d="M6 8V1h1v6.117L8.743 6.07a.5.5 0 0 1 .514 0L11 7.117V1h1v7a.5.5 0 0 1-.757.429L9 7.083 6.757 8.43A.5.5 0 0 1 6 8z"/>
                                                    <path d="M3 0h10a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2v-1h1v1a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v1H1V2a2 2 0 0 1 2-2z"/>
                                                    <path d="M1 5v-.5a.5.5 0 0 1 1 0V5h.5a.5.5 0 0 1 0 1h-2a.5.5 0 0 1 0-1H1zm0 3v-.5a.5.5 0 0 1 1 0V8h.5a.5.5 0 0 1 0 1h-2a.5.5 0 0 1 0-1H1zm0 3v-.5a.5.5 0 0 1 1 0v.5h.5a.5.5 0 0 1 0 1h-2a.5.5 0 0 1 0-1H1z"/>
                                                </svg>
                                                我的课程
                                            </div>
                                        </a>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </li>
                    <li class="nav-item">
                        <!--导航栏右-退出区-->
                        <div class="cancel">

                            <a class="nav-link" id="cancel" href="/logout">退出</a>

                            <!--退出二级菜单-->
                            <div class="menu cancel-menu">
                                <div>好好学习，天天向上</div>
                            </div>

                        </div>
                    </li>
                </ul>
            </div>
        </nav>


        <!-- 头像模态框 -->
        <div class="modal fade" id="avatar-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
            <div class="modal-dialog modal-lg" style="max-width: 870px;">
                <div class="modal-content">

                    <!-- 模态框头部 -->
                    <div class="modal-header" >
                        <h4 class="modal-title">上传头像</h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>

                    <!-- 模态框主体 -->
                    <div class="modal-body">
                        <div class="avatar-body">
                            <div class="avatar-upload">
                                <input type="file" id="file" name="file" style="display: none">
                                <input class="btn btn-outline-primary" id="uploadBtn" type="button" value="选择头像" accept=".jpg,.jpeg,.png,.bmp">
                            </div>
                            <div class="row">
                                <div class="col-md-9">
                                    <div class="avatar-wrapper">
                                        <!--生成img标签-->
                                    </div>
                                </div>
                                <div class="col-md-3 preview-wrapper">
                                    <div class="preview lg"></div>
                                    <div class="preview md"></div>
                                    <div class="preview sm"></div>
                                </div>
                            </div>
                            <div class="offset-md-9 col-md-3">
                                <button type="button" id="avatarSummit" class="btn btn-outline-success">保存修改</button>
                            </div>
                        </div>
                    </div>
                    <!-- 模态框底部 -->
                    <div class="modal-footer">
                        <!--<button type="button" class="btn btn-danger" data-dismiss="modal" id="confirmAvatar">确定</button>-->
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    </div>

                </div>
            </div>
        </div>
        <div class="loading" aria-label="Loading" role="img" tabindex="-1"></div>

        <!--修改密码模态框-->
        <div class="modal fade" id="loginInfoModal" >
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <!-- 模态框头部 -->
                    <div class="modal-header">
                        <h4 class="modal-title">修改信息</h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <!-- 模态框主体 -->
                    <div class="modal-body">
                        <!--用户信息表单-->
                        <form id="loginInfoForm">
                            <div class="form-group">
                                <label for="originalPsd">用户原密码</label>
                                <input type="password" class="form-control" v-model="originalPsd" id="originalPsd" required>
                                <small class="form-text text-muted">提示信息</small>
                            </div>
                            <div class="form-group">
                                <label for="newPsd">新密码</label>
                                <input type="password" class="form-control" v-model="newPsd" id="newPsd" required>
                            </div>
                            <div class="form-group">
                                <label for="confirmNewPsd">确认新密码</label>
                                <input type="password" class="form-control" v-model="confirmNewPsd" id="confirmNewPsd" required>
                            </div>
                            <!--
                            <div class="form-group">
                            <label for="confirmNewPsd">电子邮箱</label>
                            <input type="email" class="form-control" name="email" id="email">
                            <small class="form-text text-muted">如果填写邮箱则会发送一封带有密码更改</small>
                        </div>-->
                        </form>
                    </div>
                    <!-- 模态框底部 -->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger" @click="loginInfoUpdate">确定</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

</template>



<script>
    module.exports = {
        //props : ['info'],
        data() {
            return {
                //avatar : '',
                //username : '',
                originalPsd : '',
                newPsd : '',
                confirmNewPsd : '',
            };
        },
        components: {

        },
        methods : {
            loginInfoUpdate(){//确认更新，真正的更新方法
                if (this.$data().originalPsd === "" || this.newPsd === "" || this.confirmNewPsd === ""){
                    Qmsg.warning("请填写密码",{position:'center',timeout:2000});return false;
                }else {
                    if (this.newPsd === this.confirmNewPsd){
                        axios({
                            method : "POST",
                            url:"/modify",
                            params: {
                                originalPsd : this.originalPsd,
                                newPsd : this.newPsd,
                                confirmNewPsd : this.confirmNewPsd,
                            },
                            headers:{
                                'Content-type': 'application/x-www-form-urlencoded'
                            },
                        }).then((response)=>{
                            if (response.data.msg === "修改成功"){
                                Qmsg.success(response.data.msg,{position:'center',timeout:2000});
                                $("#loginInfoModal").modal('hide')
                            }else {
                                Qmsg.info(response.data.msg,{position:'center',timeout:2000});
                            }
                        }).catch(function (error) {
                            Qmsg.info("修改失败",{position:'center'});
                        });
                    }else {
                        Qmsg.warning("密码不一致",{position:'center',timeout:2000});return false;
                    }
                }
                this.originalPsd = ""
                this.newPsd = ""
                this.confirmNewPsd = ""
            },
        },

    }

    /*头像上传*/
    $(function () {
        let file = $("#file");
        let avatarSummit = $("#avatarSummit")
        let avatar_wrapper = $(".avatar-wrapper")
        let img,cropper,base64;

        //使用button的click代替file的click
        $("#uploadBtn").click(function () {
            file.prop("accept",".jpg,.jpeg,.png,.bmp")
            file.click()
        })

        //选择图片后触发，使用base64编码该图片并传给候选框
        file.change(function () {
            let suffixArr = ['jpg','jpeg','png','bmp'];
            let name = $(this).val()
            let prefix = name.substring(name.lastIndexOf('\\') + 1);
            let suffix = name.substring(name.lastIndexOf('.') + 1);
            console.log('文件路径:' + prefix);
            console.log('文件名:' + prefix);
            console.log('后缀名:' + suffix);

            if (!suffixArr.includes(suffix)){
                Qmsg.warning("文件类型错误，请重新选择",{position:'center', autoClose:false});
                $('#avatar-modal').modal('hide')
                return false;
            }
            getBase64($(this));//得到该图片的base64数据
            $(this).val("")//清除file内容以便重置change事件监听

        })

        //点击保存时触发，获取待裁剪的图片并上传
        avatarSummit.click(function () {
            getRoundedCanvas();
        })

        /**
         abort/none	中断读取
         readAsBinaryString/file	将文件读取为二进制码
         readAsDataURL/file	将文件读取为 DataURL
         readAsText/file, [encoding]	将文件读取为文本
         */
        function getBase64(element) {
            //获取input[type=file]的文件对象
            let file = element.get(0).files.item(0);
            if (file) {
                //使用流读取文件
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    base64 = e.target.result;
                    img = document.createElement("img");
                    img.src = base64;
                    avatar_wrapper.empty().append(img);
                    cropper = new Cropper(img,options)
                };
            }
        }

        function getRoundedCanvas(){
            let sourceCanvas = cropper.getCroppedCanvas({
                width: 128,
                height: 128,
                minWidth: 128,
                minHeight: 128,
                fillColor: '#fff',
                imageSmoothingEnabled: true,
                imageSmoothingQuality: 'high',
            });
            let canvas = document.createElement('canvas');
            let context = canvas.getContext('2d');

            let width = sourceCanvas.width;
            let height = sourceCanvas.height;
            canvas.width = width;
            canvas.height = height;
            context.imageSmoothingEnabled = true;
            context.drawImage(sourceCanvas, 0, 0);
            context.globalCompositeOperation = 'destination-in';//设置或返回如何将一个源（新的）图像绘制到目标（已有的）的图像上

            //创建img标签并添加属性
            let imgElement = document.createElement('img');
            imgElement.className = "img-fluid rounded-circle img-thumbnail";
            imgElement.src = canvas.toDataURL('image/jpeg');

            //生成img添加到头像和二级菜单头像区，使用深度克隆
            $("#avatar").empty().append(imgElement.cloneNode())
            $(".avatar-menu-img").empty().append(imgElement.cloneNode())

            // 通过canvas调用toBlob方法获取blob对象，传入一个回调函数，这个回调函数的参数就是blob对象
            canvas.toBlob(function (blob) {
                let file =  new File([blob], 'a.jpg', {type: 'image/jpg'})

                // ajax上传文件不能像上传普通对象那样，得用上FormData
                let formData = new FormData()
                formData.append("file", file)

                $.ajax({
                    type:"POST",
                    url:"/file/avatar/",
                    data : formData,
                    processData: false,    // processData和contentType必须指定为false
                    contentType: false,
                    cache: false,
                    success: (data)=> {
                        console.log(data)
                        if (data.msg === "上传成功"){
                            $('#avatar-modal').modal('hide')
                            Qmsg.success("上传成功",{position:'center'});
                        }
                    },
                })
            });
        }

        let options = {
            viewMode:16/9,//定义cropper的视图模式
            aspectRatio: 1,//裁剪框的宽高比
            dragMode:"move",//‘crop’: 可以产生一个新的裁剪框3 ‘move’: 只可以移动3 ‘none’: 什么也不处理
            preview:".preview",
            responsive:true,//—在调整窗口大小的时候重新渲染cropper
            modal:true,//黑色遮罩
            guides:false,//显示在裁剪框上方的虚线。
            autoCropArea:0.7,//定义自动裁剪面积大小(百分比)和图片进行对比。
            movable:true,//是否允许可以移动后面的图片
            rotatable:true,//是否允许旋转图像。
            scalable:true,//是否允许缩放图像。
            zoomable:true,//是否允许放大图像。
            cropBoxResizable:true,//是否通过拖动来调整剪裁框的大小。
            ready : function () {
                //console.log("准备完毕")
            },
        }
    })

    /*头像二级菜单*/
    $(function () {
        let avatar_container = $(".avatar-container");
        let avatar_menu = $(".avatar-menu");

        avatar_container.hoverIntent({
            sensitivity: 6,//滑鼠滑動的敏感度,最少要設定為1
            interval: 100,//滑鼠滑過後要延遲的秒數
            over: function () {//滑鼠滑過要執行的函式
                $(this).addClass("hover")
                avatar_menu.stop(true,true).fadeIn(400);
            },
            timeout: 0,//滑鼠滑出前要延遲的秒數
            out: function () {}//滑鼠滑出要執行的函式
        });

        avatar_menu.hoverIntent({
            sensitivity: 3,
            interval: 0,
            over: function () {},
            timeout: 200,
            out: function () {
                $(this).stop(true,true).fadeOut(200);
                avatar_container.removeClass("hover")
                console.log("移出了")
            }
        });

        /*退出二级菜单*/
        let cancel = $("#cancel")
        let cancel_menu = $(".cancel-menu");

        cancel.hoverIntent({
            sensitivity: 3,//滑鼠滑動的敏感度,最少要設定為1
            interval: 100,//滑鼠滑過後要延遲的秒數
            over: function () {//滑鼠滑過要執行的函式
                cancel_menu.stop(true,true).fadeIn("slow");
            },
            timeout: 100,//滑鼠滑出前要延遲的秒數
            out: function () {
                cancel_menu.stop(true,true).fadeOut("slow")
            }//滑鼠滑出要執行的函式
        });

    })
    /*跳转标签控制*/
    $(function () {
        let navLink = $(".nav-link:not(.ml-auto .nav-link)");
        let url = window.location.pathname;
        let realUrl,substrUrl;

        //获取地址栏url
        url = url.substring(url.lastIndexOf('/') + 1, url.length);
        //console.log(url);

        navLink.each(function () {
            //获取导航栏href属性url
            realUrl = $(this).prop("href");
            substrUrl = realUrl.substr(realUrl.lastIndexOf('/') + 1)
            if (substrUrl === url){
                $(this).addClass("active").siblings().removeClass("active")
            }
        })
    })

    module.exports = {
        data() {
            return {
                showArrowDiv: true,
                isActive: true,
                aa: 123,
            };
        },
        methods:{
            change(){
                this.isActive = !this.isActive
            }
        },
        watch:{
            isActive(newName, oldName){
                console.log(newName)
            }
        }
    }
</script>
<style scoped>
    /*头像上传*/
    .avatar-wrapper{
        width: 621px;
        height: 364px;
        margin-top: 15px;
        box-shadow: inset 0 0 5px rgba(0,0,0,.25);
        background-color: #fcfcfc;
        overflow: hidden;
    }
    .sm{
        width: 50px;
        height: 50px;
    }
    .md{
        width: 100px;
        height: 100px;
    }
    .lg{
        width: 184px;
        height: 184px;
    }
    .preview{
        margin-top: 10px;
        overflow: hidden;
        border-radius: 50%;
        border: 1px solid #eee;
        background-color: #fff;
    }
    .preview:hover{
        border-color: #ccf;
        box-shadow: 0 0 5px rgba(0,0,0,.15);
    }
    .preview-wrapper{
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    /*头像*/
    .avatar-li{
        width: 45px;
        cursor: pointer;
        margin-right: 20px;
    }
    .img-thumbnail{
        /*头像边框*/
    !important;padding: 1px;
    }
    .avatar-container{
        z-index: 2;
        position: relative;
        cursor: pointer;
        display: inline-block;
        margin-right: 10px;
        width: 36px;
        height: 36px;
        transition: transform 0.2s ease;
        background-size: cover;
        border-radius: 50%;
    }
    .hover{
        transform: translate(2px,20px);
    }
    /*二级菜单*/
    .menu{
        cursor: default;
        border: 1px solid #ebeef5;
        z-index: 100;
        top: 34px;
        position: absolute;
        background: #fff;
        min-width: 150px;
        border-radius: 4px;
        padding: 12px;
        color: #606266;
    }
    .avatar-menu{
        display: none;
        width: 280px;
        top: 24px;
        left: -124px;
        box-shadow: rgba(0, 0, 0, 0.2) 0 3px 6px ;
    }

    .avatar-menu-img{
        cursor: pointer;
        position: absolute;
        width: 68px;
        height: 68px;
        border-radius: 50%;
        top: -34px;
        left: calc(50% - 34px);
        z-index: 10000;
    }
    .avatar-menu-img img{
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
    }
    .avatar-menu-content{
        width: 100%;
        height: 100%;
        padding-top: 25px;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .avatar-menu-content p{
        color: rgb(251, 114, 153);
        font-weight: 600;
        text-align: center;
        font-size: 16px;
    }
    .avatar-menu-content span{
        width: 55px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        background-color: #FB7299;
        color: #FFFFFF;
        font-size: 12px;
        border-radius: 2px;
    }
    .avatar-container .links{
        width: 100%;
        border-bottom: 1px solid #f4f4f4;
        padding: 7px 0;
    }
    .links .link-item{
        cursor: pointer;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-pack: justify;
        justify-content: space-between;
        -ms-flex-align: center;
        align-items: center;
        transition: .3s ease;
        padding: 8px 23px;
    }
    .links .link-item:hover{
        background-color: #e5e5e5;
    }
    .links .link-title{
        font-size: 14px;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
    }
    .links .link-title svg{
        margin-right: 5px;
    }

    /*等级信息*/
    .level{
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;
        width: 100%;
    }
    .level span{
        background-color: transparent;
        color: #000000;
    }
    .level-bar{
        cursor: pointer;
        width: 240px;
        height: 2px;
        background-color: #f4f4f4;
        position: relative;
        margin: 4px 0;
    }
    .level-progress{
        position: absolute;
        background: #f3cb85;
        border-radius: 2px;
        width: 80%;
        height: 2px;
        top: 0;
        left: 0;
    }

    /*退出*/
    .cancel{
        position: relative;
    }
    #cancel{
        cursor: pointer;
        position: relative;
        color: #fff;
        font-size: 14px;
        display: block;
        width: 100px;
        height: 36px;
        line-height: 36px;
        text-align: center;
        background: #FB7299;
        border-radius: 2px;
        margin-left: 14px;
        padding: 0;!important;
    }
    .cancel-menu{
        position: absolute;
        width: 200px;
        display: none;
        top: 58px;
        right: -15px;
        filter: drop-shadow(0 0 5px #ccc);
    }
    .cancel-menu:after{
        content: "";
        position: absolute;
        left: 75%;
        top: -8px;
        width: 15px;
        height: 15px;
        background-color: #fff;
        transform: rotate(45deg);
    }
</style>